<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no">
    <title>列表页</title>
    <!-- Bootstrap core CSS -->
    <link th:href="@{/css/bootstrap.min.css}" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css">
</head>
<body>
<!--导入模板中的头部导航栏-->
<div th:replace="~{common::topbar(active='list')}"></div>
<p></p>
<div class="container">
    <div class="row vh-100">
        <!-- 中间好友列表栏-->
        <div class="col-3 h-100 border" id="friendListView">
        <!-- 等后端加载数据-->
        </div>
        <!-- 右侧聊天界面-->
        <div class="col-8 h-100 border" id="chatView">
            <!-- 等后端加载数据-->
        </div>
    </div>
</div>

<script th:src="@{/js/jquery.js}"></script>
<script th:src="@{/js/bootstrap.bundle.min.js}"></script>
<script th:src="@{/js/bootstrap.js}"></script>
<script th:inline="javascript">
    //上来加载好友列表
    $(document).ready(function(){
        $.ajax({
            type:"GET",
            url: "/user/list?accountId=" + [[${session.accountId}]],
            success: function(data) {
                console.log(data)
                //后端处理模板引擎，将抽取出的模板填充数据，并循环，然后在这里将处理好的html语言加入到对应的页面中！！！！！
                //这里是重点！！！！！！
                $("#friendListView").html(data);
            }
        });
        setInterval(keepAlive, 10000);
    })
    // 声明元素
    var ws = new WebSocket("ws://81.68.195.172:8087/chat");
    // ws连接成功事件
    ws.onopen = function(evt) {
        console.log("Connection open ...");
        // 连接成功之后发送确认身份信息
        var sendmsg = {
            "msgType":0,
            "accountId":[[${session.accountId}]],
            "token":[[${session.token}]]
        }
        var msg = JSON.stringify(sendmsg);
        ws.send(msg);
        alert("登录成功")
    };
    // ws收到消息事件
    ws.onmessage = function(evt) {
        console.log("Received Message: " + evt.data);
        //解析收到的json内容，判断发送者和发送内容
        var msgObj = JSON.parse(evt.data);
        console.log(msgObj.senderName)
        console.log(msgObj.msgInfo)
        //判断当前是谁的聊天框，才能将信息加载上去
        var name = document.getElementById(`receiverId`).innerText;
        console.log(name)
        //如果当前是正在聊天的人，则上到聊天框中，如果不是，则在对应好友列表中的脚标设置为1
        switch (msgObj.msgType) {
            case 1:
                if (name == msgObj.senderName){
                    //websocket发送完成后，需要上到聊天框中
                    var msg_area = document.getElementById("msg_area");
                    var insertHtml = '<div class="alert alert-primary" role="alert">' + msgObj.senderName + ' : ' + msgObj.msgInfo + '</div>'
                    console.log(insertHtml)
                    msg_area.insertAdjacentHTML("beforeEnd",insertHtml)
                    document.getElementById('msg_area').scrollTop = document.getElementById('msg_area').scrollHeight;
                } else {
                    document.getElementById('friend'+msgObj.accountId).innerText = "新消息"
                }
                break
            case 5:
                console.log(msgObj)
                break
            default:
                break
        }
    };
    // ws关闭事件
    ws.onclose = function(evt) {
        console.log("Connection closed.");
        alert("您已断开连接，请刷新")
    };
    function pullMsg(userId) {
        $.ajax({
            type:"GET",
            url: '/chat/msg/' + userId,
            success: function(data) {
                console.log(data)
                //后端处理模板引擎，将抽取出的模板填充数据，并循环，然后在这里将处理好的html语言加入到对应的页面中！！！！！
                //这里是重点！！！！！！
                $("#chatView").html(data);
                //每次都滚动到底部
                document.getElementById('msg_area').scrollTop = document.getElementById('msg_area').scrollHeight;
                //同时将对应的未读消息清零
                document.getElementById('friend'+userId).innerText = "0"
            }
        });
    }
    function sendmsg(userId) {
        var text = document.getElementById("msg_send")
        var info = text.value;//获取textarea中的内容
        var sendmsg = {
            "msgType":1,
            "accountId":[[${session.accountId}]],
            "senderName":[[${session.userName}]],
            "token":[[${session.token}]],
            "sendToId":userId,
            "msgInfo":info
        }
        var msg = JSON.stringify(sendmsg);
        ws.send(msg);
        //websocket发送完成后，需要上到聊天框中
        var msg_area = document.getElementById("msg_area");
        var insertHtml = '<div class="alert alert-primary" role="alert">' + [[${session.userName}]] + ' : ' + info + '</div>'
        msg_area.insertAdjacentHTML("beforeEnd",insertHtml)
        document.getElementById('msg_area').scrollTop = document.getElementById('msg_area').scrollHeight;
        //清空输入框
        $("#msg_send").val('');
    }
    function keepAlive(){
        var sendmsg = {
            "msgType":5,
            "msgInfo":"ping"
        }
        var msg = JSON.stringify(sendmsg);
        ws.send(msg);
    }
</script>
</body>
</html>